<template>  
  <div class="system-sensors-edit">
    <el-dialog v-model="isShowDialog" width="1200px" :close-on-click-modal="false" :destroy-on-close="true">
      <template #header>
        <div v-drag="['.system-sensors-edit .el-dialog', '.system-sensors-edit .el-dialog__header']">{{title}}</div>
      </template>
     <div>
      <span>时间范围：</span>
      <el-date-picker
      v-model="value1"
      type="datetimerange"
      range-separator="至"
      value-format="YYYY-MM-DD hh:mm:ss"
      start-placeholder="开始日期"
      end-placeholder="结束日期" @change="onSelectTime">
    </el-date-picker>
     </div>
      <div class="echarts_info" ref="echarts_info">
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="onCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { reactive, toRefs, defineComponent,ref,unref,getCurrentInstance } from 'vue';
import { ElMessage,} from 'element-plus';
import {
  addSensors,
  updateSensors,  listByCreateTime
} from "/@/api/system/sensors";
import * as echarts from 'echarts';
import 'echarts-gl';

export default defineComponent({
  name:"index",
  props:{    
    statusOptions:{
      type:Array,
      default:()=>[]
    },  
      roleLists:{
      type:Array,
      default:()=>[]
    },     
  },
  setup(props,{emit}) {    
    const {proxy} = <any>getCurrentInstance()
    const formRef = ref<HTMLElement | null>(null);
    const menuRef = ref();    
    const state = reactive({
      loading:false,
      isShowDialog: false,
      form:{
        imei: '',
					start: '2024-06-01 00:00:00',
					end: '2024-08-04  00:00:00'
      },
      value1:[],
      list:[] as any,
      myChart:null as any,
      title:''
    });
    const onSelectTime=(val:any)=>{
        state.form.start=val[0]
        state.form.end=val[1]
         getDetail()
    }
    const formatDate=(time:any) =>{ //定义日期格式化函数
	let date = new Date(time)
	var year = date.getFullYear(); //获取年份
	var month = date.getMonth() + 1; //获取月份，从0开始计数，所以要加1
	var day = date.getDate(); //获取日期
	month = month < 10 ? '0' + month : month; //如果月份小于10，前面补0
	day = day < 10 ? '0' + day : day; //如果日期小于10，前面补0
	return year + "-" + month + "-" + day; //拼接成yyyymmdd形式字符串
}
    // 打开弹窗
    const openDialog = (row: any) => {
      resetForm(); 
      state.title=row.name
      state.form.imei=row.imei
      state.form.start=formatDate(new Date())+ ' ' + '00:00:00'
      state.form.end=getTime_s(new Date())
      state.value1=[ state.form.start, state.form.end]
      getDetail()
      state.isShowDialog = true;
    };
    const getDetail=()=>{
      listByCreateTime(state.form).then((res:any)=>{
          if (res.data.list && res.data.list.length) {
							state.list = setInfo(res.data.list)
              setChart()
						} else {
							state.list = {
								arr: [],
								xData: []
							}
              setChart()
						}
      })
    }
    const getTime_s=(timestamp:any)=> {
				let date = new Date(timestamp)
				let Year = date.getFullYear()
				let Moth =
					date.getMonth() + 1 < 10 ?
					"0" + (date.getMonth() + 1) :
					date.getMonth() + 1
				let Day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate()
				let Hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours()
				let Minute =
					date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()
				let Sechond =
					date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds()
				let GMT =
					Year +
					"-" +
					Moth +
					"-" +
					Day +
					" " +
					Hour +
					":" +
					Minute +
					":" +
					Sechond
				return GMT
			}
    const setChart=()=>{
      if (state.myChart) {
					state.myChart.dispose()
				}
        state.myChart = echarts.init(proxy.$refs.echarts_info);
      let options ={}
      if(state.list.arr.length<=0){
        options = {
							title: {
								text: ' {a|}',
								x: 'center',
								y: 'center',
								subtext: '暂无数据',
								itemGap: -20,
								textStyle: {
									rich: {
										a: {
											color: '#000',
											fontSize: '16',
											height: 80,
											width: 160,
											backgroundColor: {
												image: '',
											}
										},
									}
								},
								subtextStyle: {
									fontSize: 16,
								}
							}
						}
      }else{
        options = {
          legend: {
            left: 'center',
            top: '2%'
          },
          grid: {
            left: '10%',
            right: '2%',
            bottom: '5%',
            top: '15%'
          },
          // title: {
          // 	left: 'center',
          // 	text: '曲线图'
          // },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data:  state.list.xData
          },
          yAxis: {
            type: 'value',
            // boundaryGap: [0, '100%']
          },
          dataZoom: [{
              type: 'inside',
              start: 0,
              end: 100
            }, 
            {
              start: 0,
              end: 100
            }
          ],
          series: state.list.arr
        };
      }
      state.myChart.setOption(options);
      window.addEventListener('resize', () => {
        state.myChart.resize()
						});
    }
  
    // 数据处理
			const setInfo=(arr:any)=> {
				let obj1 = {
					type: 'line',
					symbol: 'none',
					sampling: 'lttb',
					itemStyle: {
						color: 'rgb(0, 170, 255)'
					},
					data: []
				}
				obj1.name = '振动振幅'
				let obj2 = {
					type: 'line',
					symbol: 'none',
					sampling: 'lttb',
					itemStyle: {
						color: 'rgb(170, 255, 101)'
					},
					data: []
				}
				obj2.name = 'x轴倾斜角度'
				let obj3 = {
					type: 'line',
					symbol: 'none',
					sampling: 'lttb',
					itemStyle: {
						color: 'rgb(255, 166, 251)'
					},
					data: []
				}
				obj3.name = 'y轴倾斜角度'
				let obj4 = {
					type: 'line',
					symbol: 'none',
					sampling: 'lttb',
					itemStyle: {
						color: 'rgb(206, 85, 87)'
					},
					data: []
				}
				obj4.name = '频率'
				let obj5 = {
					type: 'line',
					symbol: 'none',
					sampling: 'lttb',
					itemStyle: {
						color: 'rgb(255, 255, 0)'
					},
					data: []
				}
				obj5.name = '设备温度'
				let obj6 = {
					type: 'line',
					symbol: 'none',
					sampling: 'lttb',
					itemStyle: {
						color: 'rgb(255, 70, 131)'
					},
					data: []
				}
				obj6.name = '速度'
				let xData = []
				arr.forEach(item => {
					// 振动振幅，weiyi 
					// qx qy倾斜角度 pl频率 temp 设备温度 sudu速度
					obj1.data.push(item.weiyi)
					obj2.data.push(item.qx)
					obj3.data.push(item.qy)
					obj4.data.push(item.pl)
					obj5.data.push(item.temp)
					obj6.data.push(item.sudu)
					let time = item.createdAt.split(' ')[1]
					xData.push(time)
				})
				return {
					arr: [obj1, obj2, obj3, obj4, obj5, obj6],
					xData
				}
			}
    // 关闭弹窗
    const closeDialog = () => {
      state.isShowDialog = false;
    };
    // 取消
    const onCancel = () => {
      closeDialog();
    };
    // 提交
    const onSubmit = () => {
      const formWrap = unref(formRef) as any;
      if (!formWrap) return;
      formWrap.validate((valid: boolean) => {
        if (valid) {
          state.loading = true;
          if(!state.formData.id || state.formData.id===0){
            //添加
          addSensors(state.formData).then(()=>{
              ElMessage.success('添加成功');
              closeDialog(); // 关闭弹窗
              emit('sensorsList')
            }).finally(()=>{
              state.loading = false;
            })
          }else{
            //修改
          updateSensors(state.formData).then(()=>{
              ElMessage.success('修改成功');
              closeDialog(); // 关闭弹窗
              emit('sensorsList')
            }).finally(()=>{
              state.loading = false;
            })
          }
        }
      });
    };
    const resetForm = ()=>{
      state.formData = {        
        id: undefined,        
        name: undefined,        
        imei: undefined,        
        status: false ,        
        temp: undefined,        
        connectTime: undefined,        
        disconnectTime: undefined,        
        qx: undefined,        
        qy: undefined,        
        pl: undefined,        
        weiyi: undefined,        
        sudu: undefined,        
        alarmCnt: undefined,        
        createdAt: undefined,        
        updatedAt: undefined,        
      }
    };    
    return {
      proxy,
      openDialog,
      closeDialog,
      onCancel,
      onSubmit,onSelectTime,
      menuRef,
      formRef,      
      ...toRefs(state),
    };
  }
})
</script>
<style scoped>  
.echarts_info{
  width: 100%;
  height: 600px;
  /* background-color: aqua; */
}
</style>